<template>
  <div>
    <div class="city-search">
      <input class="enterInput" v-model="keyword" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content" v-show="keyword" ref="search">
      <ul>
        <li
          class="search-item border-bottom"
          @click="handleClickCity(item.name)"
          v-for="item in list"
          :key="item.index">
          {{item.name}}
        </li>
        <li
          class="search-item border-bottom"
          v-show="hasNoData"
        >
            没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    city: Object
  },
  data () {
    return {
      keyword: '', // 输入框中的内容
      list: [],
      timer: null
    }
  },
  methods: {
    handleClickCity (value) {
      this.$store.dispatch('changeCity', value)
      this.$router.push({path: '/'})
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.city) {
          this.city[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scope>
@import '~styles/varibles.styl'
@import '~styles/mixins.styl'
.city-search
 background: $bgColor
 height: .84rem
 flex-row()
 justify-content: center
 flex-wrap: wrap
 align-items: center
 .enterInput
  padding: 0 .4rem
  text-align: center
  border-radius: .1rem
  height: .6rem
  width: 80%
.search-content
 position: absolute
 top: 1.7rem
 left: 0
 right: 0
 bottom: 0
 background: #eee
 overflow: hidden
 z-index: 1
 search-item
 line-height: .62rem
 padding-left: .2rem
 color: #666
</style>
